package android.sdk;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.dto.DataTransferObject;

public class NetworkController implements Runnable {
	
	private SDKClientActivity activity;
	private Socket socket;
	private ObjectOutputStream output;
	private ObjectInputStream input;
	
	public NetworkController(SDKClientActivity sdkClientActivity) {
		activity = sdkClientActivity;
	}

	public void close(){
		try {
			output.close();
			input.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void sendObject(DataTransferObject dto) {
		try {
			if (socket != null && output != null && socket.isConnected() && !socket.isClosed())
				output.writeObject(dto);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void connect(String address, int port) {
		try {
			this.socket = new Socket(address, port);
			this.output = new ObjectOutputStream(this.socket.getOutputStream());
			this.input = new ObjectInputStream(this.socket.getInputStream());
			
			new Thread(this).start();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			DataTransferObject dto = (DataTransferObject)this.input.readObject();
			while (true) {
				this.processObject(dto);
				if (socket.isConnected() && !socket.isClosed())
					dto = (DataTransferObject)this.input.readObject();
				else
					break;
			}
		} catch (OptionalDataException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void processObject(DataTransferObject dto) {
		switch (dto.getType()) {
			case DataTransferObject.ACCELEROMETER_START:
				break;
				
			case DataTransferObject.ACCELEROMETER_STOP:
				break;
				
			case DataTransferObject.ACCELEROMETER_MAXRANGE_REQUEST:
				break;	
				
			case DataTransferObject.ACCELEROMETER_RESOLUTION_REQUEST:
				break;	
				
			case DataTransferObject.ACCELEROMETER_REGISTER_EVENT:
				this.activity.registerAccelerometerEvent();
				break;	
				
			case DataTransferObject.ACCELEROMETER_UNREGISTER_EVENT:
				this.activity.unregisterAccelerometerEvent();
				break;	

			case DataTransferObject.TOUCHSCREEN_REGISTER_EVENT:
				break;	
				
			case DataTransferObject.TOUCHSCREEN_UNREGISTER_EVENT:
				break;	
				
			case DataTransferObject.TOUCHSCREEN_VIEWS_REQUEST:
				break;	
		}
	}

}
